<template>
  <a-modal class="common-modal" :title="title" :footer="null" :width="720" :visible="visible" :confirmLoading="confirmLoading" @cancel="handleCancel" :maskClosable="false" style="top:5%;">
    <a-spin :spinning="confirmLoading">
      <a-form :model="formState" @validateFields="handleOk" ref="formRef" layout="vertical" class="common-modal-content">
        <div class='blue-line mb-20'>{{$t('hangManage.baseInfo')}}</div>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item :label="$t('basicData.orderNo')" name="orderNo" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model:value.trim="formState.orderNo" :disabled="isEdit || (!isEdit && !formState.userDefined)" :placeholder="formState.userDefined ? $t('common.pleaseInput'): $t('common.systemAutoGenerate')" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('common.defined')" name="userDefined" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-switch v-model:checked="formState.userDefined" :disabled="isEdit" @change="onSwitchChange" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('basicData.customer')" name="customId" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true, message: $t('other.pleaseSelectCustomer') }]">
              <a-select v-model:value="formState.customId" allowClear :options="selectOptions.customList" :placeholder="$t('common.pleaseSelect')">
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('basicData.orderCreateDate')" name="orderDate" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-date-picker v-model:value="formState.orderDate" :placeholder="$t('common.pleaseSelect')" value-format="YYYY-MM-DD" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('basicData.PayDate')" name="deliveryDate" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-date-picker v-model:value="formState.deliveryDate" :placeholder="$t('common.pleaseSelect')" value-format="YYYY-MM-DD" />
            </a-form-item>
          </a-col>
        </a-row>
        <div class='blue-line mb-20 mt-10'>{{ $t('other.styleQuantity') }}</div>
        <a-row>
          <a-col :span="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <style-table ref="styleTable" :styleList="selectOptions.styleList" :tableData="styleList" @addType="addType" @deleteType="deleteType" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item :label="$t('common.remark')" name="remark" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea v-model:value.trim="formState.remark" :placeholder="$t('common.pleaseInput')" />
            </a-form-item>
          </a-col>
        </a-row>

      </a-form>
      <div class="common-modal-footer">
        <a-button @click="handleCancel" class="cancel">{{$t('common.cancel')}}</a-button>
        <a-button @click="handleOk" type="primary" class="confirm">{{$t('common.ok')}}</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script setup name="operateModal">
import { nextTick, ref } from 'vue';
import axios from '@/utils/request'
import { timeValue } from '@/utils'
import { cloneDeep } from 'lodash'
import StyleTable from './styleTable.vue'
import moment from 'moment'
import i18n from '@/locales/index' 
const { t } = i18n.global
const emits = defineEmits(['ok'])
const labelCol = { xs: { span: 24 }, sm: { span: 23 } }
const wrapperCol = { xs: { span: 24 }, sm: { span: 23} }
let title = ref('')
let visible = ref(false)
let isEdit = ref(false)
let confirmLoading = ref(false)
const selectOptions = ref({})
let recordInfo = ref({})
let formState = ref({})
const formRef = ref()
let styleList = ref([])

const edit = async (record, editable) => {
  initModalData(record, editable)
  await nextTick()
  formRef.value.resetFields()
  formState.value = cloneDeep(record)
}
const initModalData = (record, editable) => {
  title.value = `${record.id ? t('common.edit') : t('common.addNew')}${t('other.order')}`
  let { orderStyleList } = record
  styleList.value = orderStyleList && orderStyleList.length ? orderStyleList : [{ id: Math.random(), quantity: null, styleId: undefined }]
  record.orderDate && (record.orderDate = moment(record.orderDate).format('YYYY-MM-DD'))
  record.deliveryDate && (record.deliveryDate = moment(record.deliveryDate).format('YYYY-MM-DD'))
  recordInfo.value = Object.assign({}, record)
  visible.value = true
  isEdit.value = editable
}
const onSwitchChange = () => {
  formState.value.orderNo = null
}
const queryParams = (value) => {
  const params = cloneDeep(value)
  params.id = recordInfo.value.id
  params.orderDate = timeValue(params.orderDate)
  params.deliveryDate = timeValue(params.deliveryDate)
  params.id = recordInfo.value.id
  let orderAry = []
  styleList.value.forEach(item => {
    let { styleId, quantity } = item
    if (styleId) {
      orderAry.push({ styleId, quantity })
    }
  })
  params.orderStyleList = orderAry
  return params
}
const handleOk = async () => {
  try {
    const values = await formRef.value.validateFields();
    confirmLoading.value = true
    let url = recordInfo.value.id ? '/api/basic/order/edit' : '/api/basic/order/save'
    const res = await axios.postAction(url, queryParams(values))
    if (res.success) {
      emits('ok', res.data)
      confirmLoading.value = false
      visible.value = false
    }
  } catch (err) {
    console.log('0000000', err);
  }

  confirmLoading.value = false
};
const handleCancel = () => {
  visible.value = false
  initModalStatus()

}

const initModalStatus = () => {
  confirmLoading.value = false
  formState.value = {}
  formRef.value.resetFields()
}

const initSelectOptions = (obj) => {
  selectOptions.value = obj
}
const addType = (value) => {
  styleList.value.push(value);
}

const deleteType = (id) => {
  const dataList = styleList.value.filter(item => item.id !== id)
  styleList.value = dataList
}

defineExpose({
  edit,
  initSelectOptions
})

</script>